package com.linln.frontend.controller;


import com.linln.common.data.ArticleQueryBO;
import com.linln.common.data.PageOrder;
import com.linln.common.data.Pagination;
import com.linln.common.enums.StatusEnum;
import com.linln.common.exception.ArticleFetchFailedException;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.frontend.util.CommentTree;
import com.linln.frontend.util.laypage;
import com.linln.modules.system.domain.Article;
import com.linln.modules.system.domain.Cate;
import com.linln.modules.system.domain.Comment;
import com.linln.modules.system.domain.Tag;
import com.linln.modules.system.repository.*;
import com.linln.modules.system.service.ArticleService;
import com.linln.modules.system.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static java.util.stream.Collectors.toMap;


@Controller("frontArticleController")
@RequestMapping({"/article", "/a"})
public class ArticleController {


    private final ArticleRepository articleRepository;
    private final TagRepository tagRepository;
    private final UserRepository userRepository;
    private final CommentService commentService;
    private final CateRepository cateRepository;
    private  final CommentRepository commentRepository;
    @Autowired
    private  ArticleService articleService;
    @Autowired
    public ArticleController(ArticleRepository articleRepository,
                             TagRepository tagRepository,
                             UserRepository userRepository, CommentService commentService, CateRepository cateRepository, CommentRepository commentRepository) {
        this.articleRepository = articleRepository;
        this.tagRepository = tagRepository;
        this.userRepository = userRepository;
        this.commentService = commentService;
        this.cateRepository = cateRepository;
        this.commentRepository=commentRepository;
    }

    @RequestMapping("/{aId}")
    public String article(@PathVariable("aId") Long aId, Model model) {
        articleRepository.updateViewsById(aId);
    //    List<NBTag> list= tagRepository.findArticleTags(aId, true);
        Optional<Article> fetchArticle = articleRepository.findById(aId);
        Article article = fetchArticle.orElseThrow(() -> new ArticleFetchFailedException("未找到相关文章！"));
        List<Comment> dataNodes = commentRepository.findAllByArticleAndStatus(article, StatusEnum.OK.getCode());
        Article beforarticle = articleRepository.findbeforeArticles(article.getId());
        Article afterarticle = articleRepository.findafterArticles(article.getId());
        model.addAttribute("article", article);
        model.addAttribute("beforarticle", beforarticle);
        model.addAttribute("afterarticle", afterarticle);
        model.addAttribute("commentCount", dataNodes.size());
        model.addAttribute("comments", CommentTree.buildByRecursive(dataNodes,commentRepository));

        //normal型页面
       // model.addAttribute("cateList", cateRepository.findAll());
        return "/ArticleDetails";
    }

//    @RequestMapping("/u/{urlSeq}")
//    public String articleByUrl(@PathVariable("urlSeq") String urlSeq, Model model, Pagination<NBComment> pagination, CommentQueryBO commentQueryBO) {
//        articleRepository.updateViewsBySeq(urlSeq);
//        Optional<NBArticle> fetchArticle = articleRepository.findNBArticleByUrlSequence(urlSeq);
//        NBArticle article = fetchArticle.orElseThrow(() -> new ArticleFetchFailedException("未找到相关文章！"));
//        model.addAttribute("article", article);
//        model.addAttribute("countMsg", commentService.countByUseredIdandreade());
//        model.addAttribute("tags", tagRepository.findArticleTags(article.getId(), true));
//        model.addAttribute("author", userRepository.getOne(article.getAuthorId()).getNickname());
//        commentQueryBO.setArticleId(article.getId());
//        pagination.setLimit(10);
//
//            model.addAttribute("comments", commentService.findPageInfo(getPageable(pagination), commentQueryBO));
//            model.addAttribute("similarArticles", articleRepository.findSimilarArticles(article.getCateId(), 6));
//
//        return "frontend/content/article";
//    }

//    @RequestMapping(value = "/comments", method = RequestMethod.POST)
//    @ResponseBody
//    public Page<NBComment> comments(Pagination<NBComment> pagination, CommentQueryBO commentQueryBO) {
//        return commentService.findPageInfo(getPageable(pagination), commentQueryBO);
//    }
//
    @PostMapping("/approve")
    @ResponseBody
    public ResultVo approve(@RequestParam Long articleId) {
        return ResultVoUtil.ajaxDone(
                () -> articleRepository.updateApproveCntById(articleId) == 1,
                () -> "点赞"
        );
    }

    @RequestMapping(value = {"/pages"})
    public String pageArticle(Pagination<Article> pagination, ArticleQueryBO articleQueryBO, Model model) {
       model.addAttribute("randomArticles", articleRepository.findRandArticles(10));
//        model.addAttribute("javaArticles", articleRepository.findSimilarArticles(9,10));
//        model.addAttribute("zhiyuanArticles", articleRepository.findSimilarArticles(10,10));
 //       model.addAttribute("guidang",articleRepository.findArticleGroupByTime());
  //      model.addAttribute("tagList", tagService.findTagsTab(15));
        List<Cate> cates= cateRepository.findAll();
        model.addAttribute("cateList", cates);
        cates.forEach(cate -> {
            int n =articleRepository.countByCate(cate);
            cate.setName(String.valueOf(n));
        });
        model.addAttribute("lots", articleRepository.findLotArticles(10));
        model.addAttribute("articlesList", getArticle(pagination,articleQueryBO));
 //       model.addAttribute("countMsg", commentService.countByUseredIdandreade());

        return "/Article";
    }


    private Map<String, Object> getArticle(Pagination<Article> pagination, ArticleQueryBO articleQueryBO)
    {

        Map<String, String> orders = new HashMap<>(2);
        orders.put("top", "desc");
        orders.put("updateDate", "desc");
        Sort sort = PageOrder.getJpaSortWithOther(pagination, orders);
        Pageable pageable = PageRequest.of(pagination.getPage() - 1, 5, sort);

        Page<Article> page = articleService.findBlogArticles(pageable, articleQueryBO);
//        Map<Long, List<Tag>> articleTagsMap = page.getContent().stream()
//                .collect(toMap(
//                        Article::getId,
//                        article -> tagRepository.findArticleTags(article.getId(), true)
//                ));
        Map<String, Object> resultMap = new HashMap<>(5);

        resultMap.put("pageArticle", page.getContent());

//        resultMap.put("articleComments", commentCounts);
//        resultMap.put("articleAuthors", articleAuthorNames);
    //    resultMap.put("articleTagsMap", articleTagsMap);

        int currentPage=pagination.getPage();

        int totalPages=page.getTotalPages();
        resultMap.put("currentPage", (currentPage-1)*5);
        String url="/article/pages?page={page}";
        if (articleQueryBO.getCateId()!=null)
            url=url+"&cateId="+articleQueryBO.getCateId();
        if (articleQueryBO.getSearchStr()!=null)
            url=url+"&searchStr="+articleQueryBO.getSearchStr();
        if (articleQueryBO.getTagSearch()!=null)
            url=url+"&tagSearch="+articleQueryBO.getTagSearch();
        if (articleQueryBO.getTime()!=null)
            url=url+"&time="+articleQueryBO.getTime();
        String str= laypage.getPage(currentPage,totalPages,url);

        resultMap.put("layPage", str);
        return  resultMap;

    }



}
